package com.xiaohao.server.parkmap.controller;

import com.xiaohao.server.parkmap.entity.Article;
import com.xiaohao.server.parkmap.entity.ResponseResult;
import com.xiaohao.server.parkmap.entity.TreeAdoption;
import com.xiaohao.server.parkmap.service.ArticleService;
import com.xiaohao.server.parkmap.service.TreeAdoptionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/tree-adoption")
public class TreeAdoptionController {
    @Autowired
    private TreeAdoptionService treeAdoptionService;
    @Autowired
    private ArticleService articleService;


    @GetMapping
    public ResponseResult<List<TreeAdoption>> query(TreeAdoption treeAdoption) {
        return ResponseResult.success(treeAdoptionService.queryList(treeAdoption));
    }

    @DeleteMapping("{id}")
    public ResponseResult<Void> delete(@PathVariable Integer id) {
        return treeAdoptionService.delete(id) > 0 ? ResponseResult.success() : ResponseResult.error();
    }


    @PostMapping("adoption")
    public ResponseResult<Void> adoption(@RequestBody TreeAdoption treeAdoption) {
        TreeAdoption queryById = treeAdoptionService.queryById(treeAdoption.getId());
        if (queryById.getIsMaster().equals(1) && treeAdoption.getIsMaster().equals(1)) {
            return ResponseResult.error();
        }
        if (treeAdoption.getIsMaster().equals(1)) {
            Article article = new Article().setType(7).setTitle(queryById.getName() + "已经认养啦")
                .setThumb("https://img2.baidu.com/it/u=999033697,2587319215&fm=26&fmt=auto&gp=0.jpg");
            articleService.save(article);
        }
        return treeAdoptionService.save(treeAdoption) > 0 ? ResponseResult.success() : ResponseResult.error();
    }

    @PostMapping
    public ResponseResult<Void> update(@RequestBody TreeAdoption treeAdoption) {
        return treeAdoptionService.save(treeAdoption) > 0 ? ResponseResult.success() : ResponseResult.error();
    }
}
